package login

import (
	"crypto/md5"
	"fmt"
	"os"

	"github.com/howeyc/gopass"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func init() {
	dsn := "root:123456@tcp(172.14.1.68:3306)/classmates?charset=utf8mb4&parseTime=True&loc=Local"
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("链接数据库失败，原因是：", err.Error())
		return
	}

	fmt.Println("链接成功", DB)

}

type Classmate struct {
	ID        int
	Name      string
	Sn        string
	Sex       string
	Classname string
	Pswd      string
	QQ        string
	Haoma     string
	Money     float32
	Email     string
	ClassId   int
}

var DB *gorm.DB
var LoginUser Classmate

func Login() bool {
	var name string
	fmt.Println("请输入用户名")
	fmt.Scanln(&name)
	var pswd string
	fmt.Println("请输入密码")
	pswDBytes, err := gopass.GetPasswdPrompt("密码", true, os.Stdin, os.Stdout)
	if err != nil {
		fmt.Println("GetPasswdPrompt 失败，", err.Error())
		return false
	}
	pswd = string(pswDBytes)
	pswd = fmt.Sprintf("%x", md5.Sum([]byte(pswd)))
	//fmt.Scanln(&pswd)

	DB.Raw("SELECT*FROM classmates.classmates where name=?", name).Scan(&LoginUser)
	if LoginUser.Pswd == pswd {
		fmt.Println("登录成功")
		return true
	} else {
		fmt.Println("登录失败")
		return false
	}

}
